<script lang="ts" setup>
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { GetData, GetExcelData, GetStatisticisData, patchMarkedDelivery } from '@/api/modules/subscribercouponpackage.ts'
import storage from '@/utils/storage'

const route = useRoute()
const id = route.query.id
// 查询表单
const findFrom = reactive({
  TicketId: id as string,
  UserId: '',
  FromOrderNo: '',
  UsedOrderNo: '',
  Phone: '',
  Flag: '',
})
// 加载
const loading = ref(false)
// 数据列表
const dataList = reactive({
  list: [],
})
const total = ref(0) // 总数据数
let PageSize = 10 // 每页条数
const imgDomain = 'https://img1.eprhan.cc'

// 查询
function Inquire() {
  GetDataList(1, PageSize)
}
// 获取数据
async function GetDataList(PageIndex: number = 1, PageSize: number = 10) {
  loading.value = true
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.TicketId && { TicketId: findFrom.TicketId }),
    ...(findFrom.UserId && { UserId: findFrom.UserId }),
    ...(findFrom.FromOrderNo && { FromOrderNo: findFrom.FromOrderNo }),
    ...(findFrom.UsedOrderNo && { UsedOrderNo: findFrom.UsedOrderNo }),
    ...(findFrom.Phone && { Phone: findFrom.Phone }),
    ...(findFrom.Flag !== '' && { Flag: findFrom.Flag }),
  }

  await GetData(params).then((res: any) => {
    if (res.succeeded) {
      dataList.list = res.data.items
      total.value = res.data.total
      loading.value = false
      const data = {
        ...(findFrom.TicketId && { id: findFrom.TicketId }),
        ...(findFrom.UserId && { UserId: findFrom.UserId }),
      }
      GetStatisticis(data)
    }
    else {
      ElMessage.error('获取信息失败')
      loading.value = false
    }
  })
}

const StatisticisData = ref({
  usedCount: '',
  unusedCount: '',
  canelledCount: '',
})
function GetStatisticis(id: any) {
  GetStatisticisData(id).then((res: any) => {
    if (res.succeeded) {
      // ElMessage.success(res.message)
      StatisticisData.value = res.data
    }
  })
}

function Cancellation(id: any) {
  const params = { id }
  ElMessageBox.confirm(
    '您确定要作废吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      patchMarkedDelivery(params).then((res: any) => {
        if (res.succeeded) {
          ElMessage({
            type: 'success',
            message: '操作成功',
          })
          GetDataList()
        }
        else {
          ElMessage.error(`操作失败${res.errors}`)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消',
      })
    })
}

async function ExportExcel() {
  const params = {
    ...(findFrom.TicketId && { TicketId: findFrom.TicketId }),
    ...(findFrom.UserId && { UserId: findFrom.UserId }),
    ...(findFrom.FromOrderNo && { FromOrderNo: findFrom.FromOrderNo }),
    ...(findFrom.UsedOrderNo && { UsedOrderNo: findFrom.UsedOrderNo }),
    ...(findFrom.Phone && { Phone: findFrom.Phone }),
    ...(findFrom.Flag !== '' && { Flag: findFrom.Flag }),
  }
  try {
    const response: any = await GetExcelData(params)
    const a = document.createElement('a')
    const binaryData = []
    binaryData.push(response)
    a.href = window.URL.createObjectURL(
      new Blob(binaryData, {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;chartset=UTF-8',
      }),
    )
    a.download = (storage.local.get('fileName') as string)
    storage.local.remove('fileName')
    a.click()
    URL.revokeObjectURL(a.href)
  }
  catch (error) {
    // 请求失败处理
    console.error(error)
  }
}

// 页码
function handleSizeChange(val: number) {
  // console.log(`${val} items per page`) // 切换每页条数时触发，参数为切换后的每页条数
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  // console.log(`current page: ${val}`) // 切换时触发，参数为当前页数
  GetDataList(val, PageSize)
}

onMounted(() => {
  GetDataList()
})
</script>

<template>
  <PageMain>
    <SearchBar :show-toggle="false">
      <div class="header">
        <el-form label-positio="right" label-width="auto">
          <div class="from">
            <el-form-item v-show="false" label="券ID">
              <el-input v-model="findFrom.TicketId" style="width: 240px;" placeholder="请输入券ID" />
            </el-form-item>
            <el-form-item label="用户ID">
              <el-input v-model="findFrom.UserId" style="width: 240px;" placeholder="请输入用户ID" clearable />
            </el-form-item>
            <el-form-item label="券来源订单号">
              <el-input v-model="findFrom.FromOrderNo" style="width: 240px;" placeholder="请输入券来源订单号" clearable />
            </el-form-item>
            <el-form-item label="用券订单号">
              <el-input v-model="findFrom.UsedOrderNo" style="width: 240px;" placeholder="请输入用券订单号" clearable />
            </el-form-item>
            <el-form-item label="收货人手机号">
              <el-input v-model="findFrom.Phone" style="width: 240px;" placeholder="请输入收货人手机号" clearable />
            </el-form-item>
            <el-form-item label="券使用状态">
              <el-select v-model="findFrom.Flag" placeholder="请选择券使用状态" style="width: 240px;">
                <el-option
                  label="待使用"
                  :value="0"
                />
                <el-option
                  label="已使用"
                  :value="1"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <div class="text-right">
          <el-button @click="Inquire">
            查询
          </el-button>
        </div>
      </div>
    </SearchBar>
    <ElDivider border-style="dashed" />
    <div class="mb-5" style="display: flex; justify-content: space-between;">
      <div class="statisticis">
        <span>已使用: {{ StatisticisData.usedCount }}</span>
        <span>未使用: {{ StatisticisData.unusedCount }}</span>
        <span>已作废: {{ StatisticisData.canelledCount }}</span>
      </div>
      <el-button type="success" @click="ExportExcel">
        导出发送记录
      </el-button>
    </div>
    <ElTable v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
      <!-- <el-table-column align="center" prop="id" label="ID" width="75" /> -->
      <el-table-column align="center" prop="couponInfo.name" label="优惠券" min-width="300">
        <template #default="scope">
          <div class="user-name">
            <el-image
              :src="imgDomain + scope.row.couponInfo.picUrl"
              style="width: 50px; height: 50px; margin-right: 10px;"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><IconPicture /></el-icon>
                </div>
              </template>
            </el-image>
            <el-tag v-if="scope.row.couponInfo.type === 1">
              赠品券
            </el-tag>
            <el-tag v-else-if="scope.row.couponInfo.type === 2">
              奖品券
            </el-tag>
            <el-tag v-else-if="scope.row.couponInfo.type === 3">
              满减券
            </el-tag>
            <el-tag v-else type="warning">
              未定义
            </el-tag>
            <span style="margin-left: 10px;">
              {{ scope.row.couponInfo.name }}
            </span>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" prop="couponInfo.price" label="面值" width="100" /> -->
      <el-table-column align="center" prop="subscriberInfo.userId" label="用户ID" min-width="100" />
      <el-table-column align="center" prop="subscriberInfo.userNickName" label="顾客信息" width="200">
        <template #default="scope">
          <div v-if="scope.row.subscriberInfo.userAvatar === '' && scope.row.subscriberInfo.userNickName === '' && scope.row.subscriberInfo.userPhone === ''" class="text-center">
            未授权
          </div>
          <div v-else class="user-name">
            <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.subscriberInfo.userAvatar" />
            <div>
              <p style="margin: 0;">
                {{ scope.row.subscriberInfo.userNickName }}
              </p>
              <span>
                {{ scope.row.subscriberInfo.userPhone }}
              </span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="fromOrderNo" label="来源单号" min-width="240" />
      <el-table-column align="center" prop="orderNo" label="用券单号" min-width="240" />
      <el-table-column align="center" prop="addTime" label="获取时间" width="170" />
      <el-table-column align="center" prop="usedTime" label="使用时间" width="170" />
      <el-table-column align="center" prop="endTime" label="失效时间" width="170" />
      <el-table-column align="center" prop="flag" label="状态" width="100" fixed="right">
        <template #default="scope">
          <el-tag v-if="scope.row.flag === 1" type="success">
            已使用
          </el-tag>
          <el-tag v-else-if="scope.row.flag === -1" type="danger">
            已作废
          </el-tag>
          <el-tag v-else type="info">
            未使用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="enable" label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button type="danger" :disabled="scope.row.flag === -1 || scope.row.flag === 1" @click="Cancellation(scope.row.id)">
            作废
          </el-button>
        </template>
      </el-table-column>
    </ElTable>
    <div style="height: 10px;" />
    <el-pagination
      :page-sizes="[5, 10, 20, 50, 100]"
      size="default"
      :background="false"
      layout="total, sizes, ->, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </PageMain>
</template>

<style scoped lang="scss">
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;
  }
}

.statisticis {
  margin-bottom: 20px;
  color: rgb(121 121 121);

  span {
    margin-right: 15px;
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;

  div {
    text-align: left;
  }
}

.el-form-item {
  margin-bottom: 0;
}
</style>
